package cn.simon.controller;

import cn.simon.model.Goods;
import cn.simon.service.GoodsService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/goods")
@Log
public class GoodsController{
    @Autowired
    private GoodsService goodsService;

    @GetMapping("/getAllGoods")
    public String goodsList(Model model){
        List<Goods> list = goodsService.findAll();
        model.addAttribute("list",list);
        return "goodsList";
    }

    @GetMapping("/addGoods")
    public String addGoods(){
        return "addGoods";
    }
    @PostMapping("/addGoods")
    public String addGoods(@RequestParam("picture") MultipartFile picture, Goods goods) throws IOException {
        log.info("===============");
        if (picture.getSize() != 0){
            String filename = picture.getOriginalFilename();
            String fileUrl = "E:\\code\\bytecollege\\project\\digitalMall\\src\\main\\resources\\static\\img\\"+filename;
            picture.transferTo(new File(fileUrl));
            goods.setGoodsPicture("img/"+filename);
        }
        goodsService.addGoods(goods);
        int sellerId = goods.getSellerId();
        return "redirect:/goods/findBySellerId/"+sellerId;
    }
    @GetMapping("/findBySellerId/{id}")
    public String findBySellerId(@PathVariable("id")Integer id, Model model){
        List<Goods> list = goodsService.findBySellerId(id);
        model.addAttribute("list",list);
        return "goods";
    }
    @GetMapping("/deleteByGoodsId")
    public String deleteByGoodsId(Integer id,Integer sellerId){
        goodsService.deleteByGoodsId(id);
        return "redirect:/goods/findBySellerId/"+sellerId;
    }
    @GetMapping("updateByGoodsId")
    public String updateByGoodsId(Integer id,Integer sellerId){
        goodsService.updateByGoodsId(id);
        return "redirect:/goods/findBySellerId/"+sellerId;
    }
    @GetMapping("/updateGoods")
    public String updateGoods(Integer id,Model model){
        Goods goods = goodsService.findByGoodsId(id);
        model.addAttribute("goods",goods);
        return "updateGoods";
    }
    @PostMapping("/updateGoods")
    public String updateGoods(Goods goods){
        goodsService.updateGoods(goods);
        int sellerId = goods.getSellerId();
        return "redirect:/goods/findBySellerId/"+sellerId;
    }
}
